package oop.controller.action.teststruct;

import java.sql.SQLException;
import java.util.List;

import oop.controller.action.DefaultAction;
import oop.data.TestStructure;
import oop.db.dao.TestStructureDAO;

public class EditAction extends DefaultAction {

	protected TestStructure testStructure;

	@Override
	public void performImpl() throws Exception {
		long id = Long.parseLong(request.getParameter("tse_id"));
		List<TestStructure> testStructures = TestStructureDAO.fetchById(id);
		if (testStructures.isEmpty()) {
			request.setAttribute("message", "Không tìm thấy đề thi: " + id);
			setNextAction("error");
			return;
		}
		testStructure = testStructures.get(0);
		request.setAttribute("testStruct", testStructure);

		String submit = request.getParameter("tse_submit");
		if ("update".equals(submit)) {
			try {
				testStructure.setName(request.getParameter("tse_name"));
				testStructure.setDescription(request
						.getParameter("tse_description"));
				TestStructureDAO.persist(testStructure);

				setNextAction("teststruct.view&tsv_id=" + testStructure.getId());
			} catch (SQLException ex) {
				if (ex.getErrorCode() == 1062) {
					request.setAttribute("nameErr",
							"Tên cấu trúc đề thi đã dùng.");
				} else {
					throw ex;
				}
			}
		}
	}

}
